/**
 * 文章评论
 */
const { validationResult } = require('express-validator');
const { CODE_OK, CODE_Internal_Server_Error } = require('@root/config/index');
const { poolPromise } = require('@root/db/index');
const { validateParams } = require('@root/utils/peak-tools.js');

// /**
//  * @description 处理评论为嵌套树-只有两层
//  * @param {Array} list 所有评论
//  * @param {Number} parent_id 对应的父评论id
//  */
// function treeComment(list, parent_id) {
//   return list.filter((item) => {
//     if (item.parent_id === parent_id) {
//       item.children = treeComment(list, item.id);
//       return item;
//     }
//   });
// }

/**
 * 获取对应文章的评论列表
 *    返回树形
 */
async function selectCommentList(req, res, next) {
  if (validateParams({ req, res, validationResult })) return;
  try {
    const { user_id = '' } = req?.auth || {};
    const { article_id } = req.params;
    /* 分别 查询出一级和二级评论所需数据 , 然后以一级数据为主表 左连接关联 二级数据 */
    const oneLevelCommentSql = `select ac.*,
            u.avatar                           avatar,
            u.nickname                         nickname,
            r_u.avatar                         reply_avatar,
            r_u.nickname                       reply_nickname,
            count(acl.user_id)                 like_count,
            max(coalesce(acl.user_id = ?, 0)) user_liked
      from article_comment ac
              left join article_comment_likes acl on ac.id = acl.comment_id
              left join sys_user u
                        on ac.user_id = u.user_id
              left join sys_user r_u
                        on ac.reply_user_id = r_u.user_id
      where ac.parent_id = 0
        and ac.article_id = ?
      group by ac.id`;
    const twoLevelCommentSql = `select ac.*,
                          u.avatar                           avatar,
                          u.nickname                         nickname,
                          r_u.avatar                         reply_avatar,
                          r_u.nickname                       reply_nickname,
                          count(acl.user_id)                 like_count,
                          max(coalesce(acl.user_id = ?, 0)) user_liked
                    from article_comment ac
                            left join article_comment_likes acl on ac.id = acl.comment_id
                            left join sys_user u
                                      on ac.user_id = u.user_id
                            left join sys_user r_u
                                      on ac.reply_user_id = r_u.user_id
                    where ac.parent_id != 0
                      and ac.article_id = ?
                    group by ac.id`;
    const select_comment_sql = `
select ac1.*,
      if(max(ac2.user_id) != 0,
          json_arrayagg(
                  json_object('id', ac2.id, 'article_id', ac2.article_id, 'user_id', ac2.user_id, 'nickname',
                              ac2.nickname, 'avatar', ac2.avatar, 'create_time',
                              DATE_FORMAT(ac2.create_time, '%Y-%m-%d %H:%i:%s'), 'content', ac2.content, 'parent_id',
                              ac2.parent_id, 'reply_id', ac2.reply_id, 'reply_user_id', ac2.reply_user_id,
                              'reply_nickname', ac2.reply_nickname, 'reply_avatar', ac2.reply_avatar, 'like_count',
                              ac2.like_count, 'user_liked', ac2.user_liked)
          ),
          JSON_ARRAY()
      ) children
from (${oneLevelCommentSql}) ac1
    left join (${twoLevelCommentSql}) ac2 on ac1.id = ac2.parent_id
group by ac1.id;`;
    const [list_all] = await poolPromise.execute(select_comment_sql, [
      user_id,
      article_id,
      user_id,
      article_id,
    ]);

    res.status(CODE_OK).json({
      code: CODE_OK,
      msg: '获取评论列表成功',
      data: list_all,
    });
  } catch (error) {
    next(error);
  }
}

/**
 * 新增评论
 */
async function insertComment(req, res, next) {
  if (validateParams({ req, res, validationResult })) return;
  const { user_id } = req.auth;
  const { article_id, content, parent_id = null, reply_id = null, reply_user_id = null } = req.body;

  const connection = await poolPromise.getConnection();
  try {
    await connection.beginTransaction();
    const insert_comment_sql = `insert into article_comment (article_id, user_id,content, parent_id, reply_id, reply_user_id) values (?, ?, ?, ?, ?, ?)`;
    const [{ affectedRows }] = await connection.execute(insert_comment_sql, [
      article_id,
      user_id,
      content,
      parent_id,
      reply_id,
      reply_user_id,
    ]);
    if (!affectedRows) {
      connection.rollback();
      return res.status(CODE_Internal_Server_Error).json({
        code: CODE_Internal_Server_Error,
        msg: '新增评论失败',
      });
    }
    await connection.commit();
    res.status(CODE_OK).json({
      code: CODE_OK,
      msg: '新增评论成功',
    });
  } catch (error) {
    connection.rollback();
    next(error);
  } finally {
    connection.release();
  }
}

/**
 * 删除评论
 */
async function deleteComment(req, res, next) {
  if (validateParams({ req, res, validationResult })) return;
  // const { user_id } = req.auth;
  const { id } = req.params;
  try {
    const delete_comment_sql = `delete from article_comment where id = ?`;
    const [{ affectedRows }] = await poolPromise.execute(delete_comment_sql, [id]);
    if (!affectedRows) {
      return res.status(CODE_Internal_Server_Error).json({
        code: CODE_Internal_Server_Error,
        msg: '删除评论失败',
      });
    }
    res.status(CODE_OK).json({
      code: CODE_OK,
      msg: '删除评论成功',
    });
  } catch (error) {
    next(error);
  }
}

/**
 * 评论 点赞和取消
 */
async function articleCommentLike(req, res, next) {
  if (validateParams({ req, res, validationResult })) return;
  try {
    const { user_id } = req.auth;
    const { article_id, comment_id } = req.body;
    const select_user_comment_like_sql = `select count(*) as count from article_comment_likes where article_id = ? and comment_id = ? and user_id = ?`;
    const [[{ count }]] = await poolPromise.execute(select_user_comment_like_sql, [
      article_id,
      comment_id,
      user_id,
    ]); //  先查询判断当前用户是否点过赞

    const select_comment_like_sql = `select count(*) like_count from article_comment_likes where article_id = ? and comment_id = ?`; // 查询当前文章评论最新的点赞数量

    if (!count) {
      const insert_comment_like_sql = `insert into article_comment_likes (article_id, comment_id, user_id) values (?, ?, ?)`;
      const [{ affectedRows }] = await poolPromise.execute(insert_comment_like_sql, [
        article_id,
        comment_id,
        user_id,
      ]);
      if (!affectedRows) {
        return res.status(CODE_Internal_Server_Error).json({
          code: CODE_Internal_Server_Error,
          msg: '点赞失败',
        });
      }
      const [[{ like_count }]] = await poolPromise.execute(select_comment_like_sql, [
        article_id,
        comment_id,
      ]);
      res.status(CODE_OK).json({
        code: CODE_OK,
        msg: '点赞成功',
        data: {
          like_count,
          user_liked: 1,
        },
      });
    } else {
      const delete_comment_like_sql = `delete from article_comment_likes where article_id = ? and comment_id = ? and user_id = ?`;
      const [{ affectedRows }] = await poolPromise.execute(delete_comment_like_sql, [
        article_id,
        comment_id,
        user_id,
      ]);
      if (!affectedRows) {
        return res.status(CODE_Internal_Server_Error).json({
          code: CODE_Internal_Server_Error,
          msg: '取消点赞失败',
        });
      }
      const [[{ like_count }]] = await poolPromise.execute(select_comment_like_sql, [
        article_id,
        comment_id,
      ]);
      res.status(CODE_OK).json({
        code: CODE_OK,
        msg: '取消点赞成功',
        data: {
          like_count,
          user_liked: 0,
        },
      });
    }
  } catch (error) {
    next(error);
  }
}

module.exports = {
  selectCommentList,
  insertComment,
  deleteComment,
  articleCommentLike,
};
